<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Registration extends SB_Controller {

	function __construct()
	{
		parent::__construct();
		if ($this->user->id)
			redirect();
		$this->load->model('settings');
	}
	
	function index()
	{
		$this->getPage(array(
			'content' => $this->load->view('registration', null, true),
			'addJS' => array(base_url().'js/_carcass/registration.js'),
			'addCSS' => array(base_url().'templ/'.getTemplate().'/css/registration.css'),
			'title' => 'Регистрация'
		));
	}
	
	function ajaxReg()
	{
		if (!empty($_POST))
		{
			die($this->user->setRegEmail($_POST).'');
		}
	}
	
	function activate($code)
	{
		if ($email = $this->user->addUserByCode($code))
		{
			$this->user->startSession($email);
			redirect();
		}
		else
		{
			$this->getPage(array(
				'content' => 'Факт существования данного кода не доказан',
				'title' => 'Активация учетной записи'
			));
		}
	}

	function forgot_password($code = false)
	{
		if ($code && strlen($code)==32)
		{
			if ($rCode = $this->user->checkPasswordRestoreCode($code))
				$content = $this->load->view('restorePassword', array('code'=>$rCode), true);
			else
				$content = $this->load->view('restorePassword_fail', null, true);

			$this->getPage(array(
				'content' => $content,
				'title' => 'Восстановление пароля'
			));
		}
		else
		{
			$this->getPage(array(
				'content' => $this->load->view('forgotPassword', null, true),
				'title' => "Восстановление пароля"
			));
		}

	}

	function forgot_password_sendmail()
	{
		if (empty($_POST['email']) || !is_string($_POST['email']))
			die('Некорректный email');
		
		$this->load->model('email_model', 'mail');

		if ($this->mail->valid_email($_POST['email']))
			$email = $_POST['email'];
			else
			die('Некорректный email');

		if (!($user = $this->user->checkUser($email, false, true)))
			die('Такие здесь не числятся. Пройдите <a href="/registration">регистрацию</a>');

		$code = strtolower(random_string('alnum', 32));

		if ($this->user->addNewPasswordRestore($email, $code))
		{
			$mailData = (array)$user;
			$mailData['pCode'] = $code;
			$this->mail->sendTemplateEmail($email, 'password_recovery', $mailData);
		}
		else
			die('Ошибка базы данных, попробуйте позже');
	}

	function restorePassword()
	{
		if (empty($_POST['pass']) || empty($_POST['pass2']) || empty($_POST['code']))
			die();

		if ($_POST['pass'] != $_POST['pass2'])
			die('Пароли не совпадают');

		if (!($rCode = $this->user->checkPasswordRestoreCode($_POST['code'])))
			die('Жульничать плохо!');

		if ($rCode->dCreated < (now()-7200)) /* 2 hours*/
			die('Данный код устарел. Запросите <a href="/registration/forgot_password">восстановление пароля</a> еще раз.');

		$this->user->removeCode($rCode->pCode);

		if (!($this->user->setNewPassword($rCode->pEmail, $_POST['pass'])))
			die('Пользователь с таким email не найден. Пройдите <a href="/registration">регистрацию</a>');
	}
	
/**
 * vk.com
 *
 * http://vk.com/editapp?act=create
 * http://vk.com/apps?act=settings
 *
 */
	function vk_auth()
	{
		if ($this->settings->data->pVKAuth == '0' || $this->settings->data->pVKId == '' || $this->settings->data->pVKSecret == '')
			redirect();

		define('VK_APP_ID', $this->settings->data->pVKId);
		define('VK_APP_SECRET', $this->settings->data->pVKSecret);
		define('VK_URL_CALLBACK', base_url().'registration/vk_auth');

		define('VK_URL_ACCESS_TOKEN', 'https://oauth.vk.com/access_token');
		define('VK_URL_AUTHORIZE', 'https://oauth.vk.com/authorize');
		define('VK_URL_GET_PROFILES', 'https://api.vk.com/method/users.get');
		
		if (!empty($_GET['error']))
			redirect();

		if (empty($_GET['code']))
		{
			redirect(VK_URL_AUTHORIZE.
				'?client_id='.VK_APP_ID.
				'&scope=offline'.
				'&redirect_uri='.urlencode(VK_URL_CALLBACK).
				'&response_type=code');
		}
		else
		{
			$url = VK_URL_ACCESS_TOKEN.
				'?client_id='.VK_APP_ID.
				'&client_secret='.VK_APP_SECRET.
				'&code='.$_GET['code'].
				'&redirect_uri='.urlencode(VK_URL_CALLBACK);

			if (!($res = @file_get_contents($url)))
				redirect();
			$res = json_decode($res);
			if (empty($res->access_token) || empty($res->user_id))
				redirect();

			// если такой уже есть
			if ($this->user->checkSocAuth('vk', $res->user_id))
				redirect();
			
			$url = VK_URL_GET_PROFILES.
				'?uid='.$res->user_id.
				'&access_token='.$res->access_token;
			
			if (!($user = @file_get_contents($url)))
				redirect();
				
			$user = json_decode($user);
			
			if (empty($user->response[0]))
				redirect();
			
			$user = $user->response[0];
			if (empty($user->uid) || empty($user->first_name) || empty($user->last_name))
				redirect();

			$user_data = array(
				'pName' => $user->first_name.' '.$user->last_name,
			);
			$this->user->socAuth('vk', $res->user_id, $user_data);

			redirect();
		}
	}

/**
 * twitter.com
 *
 * https://dev.twitter.com/apps
 *
 */
	function twitter_auth()
	{
		if ($this->settings->data->pTwitterAuth == '0' || $this->settings->data->pTwitterId == '' || $this->settings->data->pTwitterSecret == '')
			redirect();

		define ('TWITTER_APP_ID', $this->settings->data->pTwitterId);
		define ('TWITTER_APP_SECRET', $this->settings->data->pTwitterSecret);
		define ('TWITTER_URL_CALLBACK', base_url().'registration/twitter_auth');

		define ('TWITTER_URL_REQUEST_TOKEN', 'https://api.twitter.com/oauth/request_token');
		define ('TWITTER_URL_AUTHORIZE', 'https://api.twitter.com/oauth/authorize');
		define ('TWITTER_URL_ACCESS_TOKEN', 'https://api.twitter.com/oauth/access_token');
		define ('TWITTER_URL_USER_DATA', 'https://api.twitter.com/1.1/users/show.json');
		define ('TWITTER_URL_GET_TOKEN', 'https://api.twitter.com/oauth2/token');
		
		session_start();
		if (empty($_GET['oauth_token']) || empty($_GET['oauth_verifier']))
		{
			$oauth_nonce = md5(uniqid(rand(), true));
			$oauth_timestamp = time();
			
			$oauth_base_text = "GET&".
				urlencode(TWITTER_URL_REQUEST_TOKEN)."&".
				urlencode("oauth_callback=".urlencode(TWITTER_URL_CALLBACK)."&").
				urlencode("oauth_consumer_key=".TWITTER_APP_ID."&").
				urlencode("oauth_nonce=".$oauth_nonce."&").
				urlencode("oauth_signature_method=HMAC-SHA1&").
				urlencode("oauth_timestamp=".$oauth_timestamp."&").
				urlencode("oauth_version=1.0");
			
			$key = TWITTER_APP_SECRET."&";
			$oauth_signature = base64_encode(hash_hmac("sha1", $oauth_base_text, $key, true));
			
			$url = TWITTER_URL_REQUEST_TOKEN.
				'?oauth_callback='.urlencode(TWITTER_URL_CALLBACK).
				'&oauth_consumer_key='.TWITTER_APP_ID.
				'&oauth_nonce='.$oauth_nonce.
				'&oauth_signature='.urlencode($oauth_signature).
				'&oauth_signature_method=HMAC-SHA1'.
				'&oauth_timestamp='.$oauth_timestamp.
				'&oauth_version=1.0';
			
			if (!($response = @file_get_contents($url)))
				redirect();
			parse_str($response, $result);
			
			$_SESSION['oauth_token_secret'] = $result['oauth_token_secret'];
			
			redirect(TWITTER_URL_AUTHORIZE.
				'?oauth_token='.$result['oauth_token']);
		}
		else
		{
			$oauth_nonce = md5(uniqid(rand(), true));
			$oauth_timestamp = time();

			if (empty($_GET['oauth_token']))
				redirect();
			$oauth_token = trim($_GET['oauth_token']);
			$oauth_verifier = trim($_GET['oauth_verifier']);
			$oauth_token_secret = $_SESSION['oauth_token_secret'];

			$oauth_base_text = "GET&".
				urlencode(TWITTER_URL_ACCESS_TOKEN)."&".
				urlencode("oauth_consumer_key=".TWITTER_APP_ID."&").
				urlencode("oauth_nonce=".$oauth_nonce."&").
				urlencode("oauth_signature_method=HMAC-SHA1&").
				urlencode("oauth_token=".$oauth_token."&").
				urlencode("oauth_timestamp=".$oauth_timestamp."&").
				urlencode("oauth_verifier=".$oauth_verifier."&").
				urlencode("oauth_version=1.0");
			
			$key = TWITTER_APP_SECRET."&".$oauth_token_secret;
			$oauth_signature = base64_encode(hash_hmac("sha1", $oauth_base_text, $key, true));
			
			$url = TWITTER_URL_ACCESS_TOKEN.
				'?oauth_nonce='.$oauth_nonce.
				'&oauth_signature_method=HMAC-SHA1'.
				'&oauth_timestamp='.$oauth_timestamp.
				'&oauth_consumer_key='.TWITTER_APP_ID.
				'&oauth_token='.urlencode($oauth_token).
				'&oauth_verifier='.urlencode($oauth_verifier).
				'&oauth_signature='.urlencode($oauth_signature).
				'&oauth_version=1.0';
			
			if (!($response = @file_get_contents($url)))
				redirect();
			
			parse_str($response, $result);

			if ($this->user->checkSocAuth('twitter', $result['user_id']))
				redirect();
			
			// узнали его имя
			$url = TWITTER_URL_USER_DATA.
				'?screen_name='.$result['screen_name'];

			$data = array(
				'grant_type' => 'client_credentials',
			);
			$opts = array('http' =>
						array(
							'method'  => 'POST',
							'header'  =>"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n".
										'Authorization: Basic '.base64_encode($this->settings->data->pTwitterId.':'.$this->settings->data->pTwitterSecret)."\r\n",
							'content' => http_build_query($data)
						)
					);
			$context  = stream_context_create($opts);
			
			// no token
			if (!($response = @file_get_contents(TWITTER_URL_GET_TOKEN, false, $context)))
				redirect();
			$result = json_decode($response);
			
			$opts = array('http' =>
						array(
							'method'  => 'GET',
							'header'  =>"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n".
										'Authorization: Bearer '.$result->access_token."\r\n",
						)
					);
			
			if (!($response = @file_get_contents($url, false, stream_context_create($opts))))
				redirect();

			$user = json_decode($response);
			if (empty($user))
				redirect();
			
			$user_data = array(
				'pName' => $user->screen_name,
			);
			$this->user->socAuth('twitter', $user->id, $user_data);

			redirect();
		}
	}

/**
 * facebook.com
 *
 * https://developers.facebook.com/apps
 *
 */
	function facebook_auth()
	{
		if ($this->settings->data->pFBAuth == '0' || $this->settings->data->pFBId == '' || $this->settings->data->pFBSecret == '')
			redirect();

		define('FB_APP_ID', $this->settings->data->pFBId);
		define('FB_APP_SECRET', $this->settings->data->pFBSecret);
		define('FB_URL_CALLBACK', base_url().'registration/facebook_auth');
		
		define('FB_URL_OATH', 'https://www.facebook.com/dialog/oauth');
		define('FB_URL_ACCESS_TOKEN', 'https://graph.facebook.com/oauth/access_token');
		define('FB_URL_GET_ME', 'https://graph.facebook.com/me');

		if (!empty($_GET['error']))
			redirect();
		
		session_start();
		
		if(empty($_GET['code']))
		{
			$_SESSION['state'] = md5(uniqid(rand(), TRUE));
			redirect(FB_URL_OATH.
				'?client_id='.FB_APP_ID.
				'&redirect_uri='.urlencode(FB_URL_CALLBACK).
				"&state=".$_SESSION['state']);
		}
		else
		{
			if (!($_SESSION['state'] && ($_SESSION['state'] === $_GET['state'])))
				die("The state does not match. You may be a victim of CSRF.");

			$url = FB_URL_ACCESS_TOKEN.
				'?client_id='.FB_APP_ID.
				'&redirect_uri='.urlencode(FB_URL_CALLBACK).
				'&client_secret='.FB_APP_SECRET.
				'&code='.$_GET['code'];
			
			if (!($response = @file_get_contents($url)))
				redirect();

			parse_str($response, $result);

			$url = FB_URL_GET_ME.
				'?fields=id,name&access_token='.$result['access_token'];
			
			if (!($user = @file_get_contents($url)))
				redirect();
			
			$user = json_decode($user);
			if (empty($user))
				redirect();

			$user_data = array(
				'pName' => $user->name,
			);
			$this->user->socAuth('fb', $user->id, $user_data);

			redirect();
		}
	}

/**
 * mail.ru
 *
 * http://api.mail.ru/sites/my/
 *
 */
	function mailru_auth()
	{
		if ($this->settings->data->pMailruAuth == '0' || $this->settings->data->pMailruId == '' || $this->settings->data->pMailruSecret == '' || $this->settings->data->pMailruPrivate == '')
			redirect();

		// sblog.coddism!!!
		define('MAILRU_APP_ID', $this->settings->data->pMailruId);
		define('MAILRU_APP_PRIVATE', $this->settings->data->pMailruPrivate);
		define('MAILRU_APP_SECRET', $this->settings->data->pMailruSecret);
		define('MAILRU_URL_CALLBACK', base_url().'registration/mailru_auth');
		
		define('MAILRU_URL_AUTHORIZE', 'https://connect.mail.ru/oauth/authorize');
		define('MAILRU_URL_GET_TOKEN', 'https://connect.mail.ru/oauth/token');
		define('MAILRU_URL_API', 'http://www.appsmail.ru/platform/api');

		if (!empty($_GET['error']))
			redirect();

		if (empty($_GET['code']))
		{
			redirect(MAILRU_URL_AUTHORIZE.
				'?client_id='.MAILRU_APP_ID.
				'&response_type=code'.
				'&redirect_uri='.urlencode(MAILRU_URL_CALLBACK));
		}
		else
		{
			$data = array(
				'client_id' => MAILRU_APP_ID,
				'client_secret' => MAILRU_APP_SECRET,
				'grant_type' => 'authorization_code',
				'code' => trim($_GET['code']),
				'redirect_uri' => MAILRU_URL_CALLBACK
			);

			$opts = array('http' =>
							array(
								'method'  => 'POST',
								'header'  =>"Content-Type: application/x-www-form-urlencoded\r\n".
											"Accept: */*\r\n",
								'content' => http_build_query($data)
							)
						);
			if (!($response = @file_get_contents(MAILRU_URL_GET_TOKEN, false, stream_context_create($opts))))
				redirect();
			
			$result = json_decode($response);
			if (empty($result))
				redirect();

			if ($this->user->checkSocAuth('mailru', $result->x_mailru_vid))
				redirect();
			
			// ключи в алфавитном порядке! ksort() если лень
			$request_params = array(
				'app_id' => MAILRU_APP_ID,
				'method' => 'users.getInfo',
				'secure' => 1,
				'session_key' => $result->access_token,
				'uids' => $result->x_mailru_vid,
			);
			
			// ksort($request_params);
			// можно удалить все & из http_build_query()
			$params = '';
			foreach ($request_params as $key => $value)
				$params .= "$key=$value";

			$url = MAILRU_URL_API.
				'?'.http_build_query($request_params).
				'&sig='.md5($params.MAILRU_APP_SECRET);
			
			if (!($user = @file_get_contents($url)))
				redirect();
			
			$user_data = json_decode($user);
			if (empty($user_data) || empty($user_data[0]))
				redirect();
			
			$data = array(
				'pName' => $user_data[0]->last_name.' '.$user_data[0]->first_name,
				'pEmail' => $user_data[0]->email,
				'pLink' => $user_data[0]->link,
				'token' => $result->access_token
			);
			$this->user->socAuth('mailru', $user_data[0]->uid, $data);

			redirect();
		}
	}
/**
 * odnoklassniki.ru
 *
 * http://www.odnoklassniki.ru/dk?st.cmd=appsInfoMyDevList&st._aid=Apps_Info_MyDev
 *
 */
	function ok_auth()
	{
		if ($this->settings->data->pOKAuth == '0' || $this->settings->data->pOKId == '' || $this->settings->data->pOKSecret == '' || $this->settings->data->pOKPublic == '')
			redirect();

		define ('OK_APP_ID', $this->settings->data->pOKId);
		define ('OK_APP_PUBLIC', $this->settings->data->pOKPublic);
		define ('OK_APP_SECRET', $this->settings->data->pOKSecret);
		define ('OK_URL_CALLBACK', base_url().'registration/ok_auth');
		
		define ('OK_URL_AUTHORIZE', 'http://www.odnoklassniki.ru/oauth/authorize');
		define ('OK_URL_GET_TOKEN', 'http://api.odnoklassniki.ru/oauth/token.do');
		define ('OK_URL_ACCESS_TOKEN', 'http://api.odnoklassniki.ru/fb.do');

		if (!empty($_GET['error']))
			redirect();

		if (empty($_GET['code']))
		{
			redirect(OK_URL_AUTHORIZE.
				'?client_id='.OK_APP_ID.
				'&response_type=code'.
				'&redirect_uri='.urlencode(OK_URL_CALLBACK));
		}
		else
		{
			$data = array(
				'code' => trim($_GET['code']),
				'redirect_uri' => OK_URL_CALLBACK,
				'client_id' => OK_APP_ID,
				'client_secret' => OK_APP_SECRET,
				'grant_type' => 'authorization_code',
			);

			$opts = array('http' =>
							array(
								'method'  => 'POST',
								'header'  =>"Content-type: application/x-www-form-urlencoded\r\n".
											"Accept: */*\r\n",
								'content' => http_build_query($data)
							)
						);

			if (!($response = @file_get_contents(OK_URL_GET_TOKEN, false, stream_context_create($opts))))
				redirect();
			
			$result = json_decode($response);
			if (empty($result->access_token))
				redirect();

			$url = OK_URL_ACCESS_TOKEN.
				'?access_token='.$result->access_token.
				'&method=users.getCurrentUser'.
				'&application_key='.OK_APP_PUBLIC.
				'&sig='.md5('application_key='.OK_APP_PUBLIC.'method=users.getCurrentUser'.md5($result->access_token.OK_APP_SECRET));
			
			if (!($response = @file_get_contents($url)))
				redirect();
			
			$user = json_decode($response);

			if (empty($user))
				redirect();

			$user_data = array(
				'pName' => $user->last_name.' '.$user->first_name,
			);
			
			$this->user->socAuth('ok', $user->uid, $user_data);
			redirect();
		}
	}
}

?>